package com.acane.instagram.feature.profile

import android.annotation.SuppressLint
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Divider
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetState
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.Scaffold
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.acane.instagram.R
import com.acane.instagram.core.config.Config
import com.acane.instagram.core.design.component.MyNavigationBar
import com.acane.instagram.core.design.theme.InstagramBlue
import com.acane.instagram.core.design.theme.InstagramLightGray
import com.acane.instagram.core.model.UserInfo
import com.acane.instagram.feature.common.SessionManager
import com.acane.instagram.feature.home.HomeViewModel
import com.acane.instagram.feature.main.MainViewModel
import com.acane.instagram.feature.main.TopLevelDestination
import com.acane.instagram.feature.me.DiscoverUsers
import com.acane.instagram.feature.me.MeViewModel
import com.acane.instagram.feature.me.ProfileStats
import com.acane.instagram.feature.me.player.VideoPostPlayer
import com.acane.instagram.feature.video.VIDEO_ROUTE
import com.google.accompanist.pager.HorizontalPager
import com.google.accompanist.pager.rememberPagerState
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

@Composable
fun ProfileRoute(
    homeViewModel: HomeViewModel = viewModel(),
    navController: NavHostController,
    viewModel: ProfileViewModel = viewModel(),
    toProfile: (String) -> Unit,
    toChat: (String) -> Unit,
    meViewModel: MeViewModel = viewModel(),
    toPost: (String, Int) -> Unit,
    toFollow: (String, String) -> Unit,
) {
    ProfileScreen(
        viewModel = viewModel,
        navController = navController,
        homeViewModel = homeViewModel,
        toProfile = toProfile,
        toChat = toChat,
        meViewModel = meViewModel,
        toPost = toPost,
        toFollow = toFollow,
    )
}

@SuppressLint("UnusedMaterialScaffoldPaddingParameter", "StateFlowValueCalledInComposition")
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun ProfileScreen(
    toProfile: (String) -> Unit,
    homeViewModel: HomeViewModel,
    viewModel: ProfileViewModel,
    navController: NavHostController,
    toChat: (String) -> Unit,
    meViewModel: MeViewModel,
    toPost: (String, Int) -> Unit,
    toFollow: (String, String) -> Unit,
    mainViewModel: MainViewModel = viewModel(),
) {
    val isFollowed = viewModel.isFollowed.collectAsState()
    val userInfo = viewModel.currentUserInfo
    val scope = rememberCoroutineScope()
    val optionBottomSheetState =
        rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)

    val notifyBottomSheetState =
        rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)

    val nestedScrollConnection = remember {
        object : NestedScrollConnection {}
    }
    val recommendUserList = homeViewModel.userDatum.value
    // 使用 collectAsState 监听数据流变化
    val gridPostList by viewModel.gridPostData.collectAsState()
    val videoPostList by viewModel.videoPostData.collectAsState()

    val (isCardListVisible, setCardListVisible) = remember { mutableStateOf(true) }

    val refreshState by viewModel.refresh.collectAsState()

    val swipeRefresh = rememberSwipeRefreshState(isRefreshing = refreshState)

    val (bottomNavBackgroundColor, setBottomNavBackgroundColor) = remember { mutableStateOf(Color.White) }
    val titles = listOf(
        Pair(R.drawable.grid, R.drawable.grid_unselected),
        Pair(R.drawable.video, R.drawable.video_unselected)
    )
    // 从ViewModel获取当前destination
    var currentDestination = mainViewModel.currentMainDestination

    // 使用pagerState同步页面状态
    val pageState = androidx.compose.foundation.pager.rememberPagerState(
        initialPage = TopLevelDestination.entries.indexOfFirst { it.route == currentDestination },
        pageCount = { TopLevelDestination.entries.size }
    )

    // 同步pager状态到ViewModel
    LaunchedEffect(pageState.currentPage) {
        val destination = TopLevelDestination.entries[pageState.currentPage].route
        mainViewModel.updateMainDestination(destination)
    }

    Box(modifier = Modifier.fillMaxSize()) {
        // options抽屉布局
        ModalBottomSheetLayout(
            sheetState = optionBottomSheetState,
            sheetShape = RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp),
            sheetContent = {
                Column(
                    verticalArrangement = Arrangement.Center,
                    modifier = Modifier.padding(top = 10.dp)
                ) {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .wrapContentSize(align = Alignment.Center)
                    ) {
                        Image(
                            painter = painterResource(id = R.drawable.bar_horizontal),
                            contentDescription = "bar",
                        )
                    }
                    Text(
                        text = "举报...",
                        modifier = Modifier.padding(top = 20.dp, start = 15.dp)
                    )
                    Text(
                        text = "拉黑",
                        modifier = Modifier.padding(top = 20.dp, start = 15.dp)
                    )
                    Text(
                        text = "帐户简介",
                        modifier = Modifier.padding(top = 20.dp, start = 15.dp)
                    )
                    Text(
                        text = "分享主页",
                        modifier = Modifier.padding(top = 20.dp, bottom = 40.dp, start = 15.dp)
                    )
                }


            }
        ) {
            SwipeRefresh(state = swipeRefresh, onRefresh = {
                viewModel.startRefresh()
            }) {
                Scaffold(
                    topBar = {
                        userInfo?.let {
                            ProfileTopBar(
                                userInfo = it,
                                viewModel = viewModel,
                                coroutineScope = scope,
                                optionBottomSheetState = optionBottomSheetState,
                                navController = navController,
                                notifyBottomSheetState = notifyBottomSheetState
                            )
                        }
                    },
                    bottomBar = {
                        MyNavigationBar(
                            destinations = TopLevelDestination.entries,
                            currentDestination = currentDestination,
                            onNavigateToDestination = { index ->
                                scope.launch {
                                    pageState.scrollToPage(index)
                                }
                            },
                            modifier = Modifier
                                .fillMaxWidth()
                                .background(bottomNavBackgroundColor)
                                .navigationBarsPadding(),
                            currentUserAvatar = SessionManager.currentUser?.avatar
                        )
                    },
                    modifier = Modifier.nestedScroll(nestedScrollConnection),
                ) { paddingValues ->
                    // 动态设置背景颜色
                    LaunchedEffect(currentDestination) {
                        setBottomNavBackgroundColor(
                            if (currentDestination == VIDEO_ROUTE) Color.Black else Color.White
                        )
                    }
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(paddingValues)
                    ) {
                        Column(
                            modifier = Modifier
                                .fillMaxSize()
                        ) {

                            // 头像和统计信息

                            userInfo?.let {
                                ProfileHeader(
                                    userInfo = it,
                                    isCardListVisible = isCardListVisible,
                                    setCardListVisible = setCardListVisible,
                                    isFollowed = isFollowed.value,
                                    toChat = toChat,
                                    toFollow = toFollow,
                                    profileViewModel = viewModel,
                                )
                            }


                            // 卡片列表
                            if (isCardListVisible) {
                                DiscoverUsers(
                                    recommendUserList = recommendUserList,
                                    toProfile = toProfile
                                )
                            }

                            // TabRow 和 Pager
                            val pagerState = rememberPagerState(initialPage = 0)
                            TabRow(
                                selectedTabIndex = pagerState.currentPage,
                                containerColor = Color.White,
                                tabs = {
                                    titles.forEachIndexed { index, (selectedIcon, unselectedIcon) ->
                                        Tab(
                                            modifier = Modifier.padding(10.dp),
                                            selected = pagerState.currentPage == index,
                                            onClick = {
                                                scope.launch {
                                                    if (index >= 0 && index < titles.size) { // 添加边界检查
                                                        scope.launch {
                                                            pagerState.animateScrollToPage(index)
                                                        }
                                                    }
                                                    //pagerState.animateScrollToPage(index)
                                                }
                                            },
                                        ) {
                                            val icon =
                                                if (pagerState.currentPage == index) selectedIcon else unselectedIcon
                                            Image(
                                                painter = painterResource(id = icon),
                                                contentDescription = "Tab Icon",
                                                modifier = Modifier.size(24.dp)
                                            )
                                        }
                                    }
                                }
                            )

                            // Pager
                            HorizontalPager(
                                count = titles.size,
                                state = pagerState,
                                modifier = Modifier.weight(1f)
                            ) { page ->
                                when (page) {
                                    0 -> {
                                        if (gridPostList.isEmpty()) {
                                            Text(
                                                text = "暂无内容",
                                                modifier = Modifier.align(Alignment.CenterHorizontally)
                                            )
                                        } else {
                                            ProfilePhotoStaggeredGrid(
                                                coverList = gridPostList,
                                                meViewModel = meViewModel,
                                                toPost = toPost,
                                                profileViewModel = viewModel,
                                            )
                                        }
                                    }

                                    1 -> {
                                        if (videoPostList.isEmpty()) {
                                            Text(
                                                text = "暂无内容",
                                                modifier = Modifier.align(Alignment.CenterHorizontally)
                                            )
                                        } else {
                                            // 安全写法：检查列表有效性
                                            val safeIndex = 0.coerceAtMost(videoPostList.lastIndex)
                                            VideoPostPlayer(videoPostList[safeIndex].urls)
                                        }
                                        //VideoStaggeredGrid(coverList = videoPostList.map { it.urls.first() })
                                    }
                                }
                            }
                            Spacer(Modifier.size(50.dp))
                        }
                    }
                }
            }
        }

        // notify抽屉布局
        ModalBottomSheetLayout(
            sheetState = notifyBottomSheetState,
            sheetShape = RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp),
            sheetContent = {
                val notifyTitles = listOf("帖子", "快拍", "Reels", "广播频道")
                LazyColumn(
                    modifier = Modifier.fillMaxSize()
                ) {
                    item {
                        Column(
                            verticalArrangement = Arrangement.Center,
                            horizontalAlignment = Alignment.CenterHorizontally,
                            modifier = Modifier.padding(top = 10.dp)
                        ) {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .wrapContentSize(align = Alignment.Center)
                            ) {
                                Image(
                                    painter = painterResource(id = R.drawable.bar_horizontal),
                                    contentDescription = "bar",
                                )
                                Text(
                                    text = "通知",
                                    modifier = Modifier.padding(top = 50.dp),
                                    //fontWeight = FontWeight.Bold,
                                    fontSize = 20.sp,
                                )
                            }
                        }
                    }

                    item {
                        Divider(
                            modifier = Modifier.padding(top = 10.dp),
                            color = InstagramLightGray
                        )
                    }

                    item {
                        notifyTitles.forEach {
                            NotifyItem(
                                title = it,
                            )
                        }
                    }
                }
            }
        ) {}
    }
}

@Composable
fun NotifyItem(title: String) {
    var checked by remember { mutableStateOf(true) }
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = title,
            modifier = Modifier.padding(top = 5.dp, start = 15.dp)
        )
        Spacer(modifier = Modifier.weight(1f)) // 推动 Switch 到最右边
        Switch(
            checked = checked,
            onCheckedChange = {
                checked = it
                Log.d("Switch", "${title}: $it")
            },
            colors = SwitchDefaults.colors(
                checkedThumbColor = MaterialTheme.colorScheme.primary,
                checkedTrackColor = MaterialTheme.colorScheme.primaryContainer,
                uncheckedThumbColor = MaterialTheme.colorScheme.secondary,
                uncheckedTrackColor = MaterialTheme.colorScheme.secondaryContainer,
            )
        )
    }
}

@SuppressLint("StateFlowValueCalledInComposition")
@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterialApi::class)
@Composable
fun ProfileTopBar(
    navController: NavHostController,
    viewModel: ProfileViewModel,
    userInfo: UserInfo,
    coroutineScope: CoroutineScope,
    optionBottomSheetState: ModalBottomSheetState,
    notifyBottomSheetState: ModalBottomSheetState,
) {
    //val userInfo = viewModel.userInfo.value
    TopAppBar(
        title = {

        },
        navigationIcon = {
            Row(
                modifier = Modifier.padding(end = 8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                androidx.wear.compose.material3.IconButton(
                    onClick = {
                        navController.popBackStack()
                    },
                    modifier = Modifier
                        .size(45.dp)
                        .padding(start = 10.dp, end = 10.dp)
                ) {
                    Image(
                        painter = painterResource(id = R.drawable.arrow_left),
                        contentDescription = "back",
                        modifier = Modifier
                            .size(30.dp)
                    )
                }
                userInfo.userName?.let {
                    Text(
                        text = it,
                        fontWeight = FontWeight.Bold,
                        fontSize = 20.sp,
                        modifier = Modifier.padding(top = 10.dp, start = 10.dp)
                    )
                }
            }
        },
        actions = {
            Row {
                if (viewModel.isFollowed.value) {
                    androidx.wear.compose.material3.IconButton(
                        onClick = {
                            coroutineScope.launch {
                                notifyBottomSheetState.show()
                            }
                        },
                        modifier = Modifier
                            .size(45.dp)
                            .padding(start = 10.dp, end = 10.dp)
                    ) {
                        Image(
                            painter = painterResource(id = R.drawable.bell_check),
                            contentDescription = "createMedia"
                        )
                    }
                }
                androidx.wear.compose.material3.IconButton(
                    onClick = {
                        // 显示底部抽屉
                        coroutineScope.launch {
                            optionBottomSheetState.show()
                        }
                    },
                    modifier = Modifier
                        .size(30.dp)
                        .padding(start = 10.dp, top = 10.dp)
                ) {
                    Image(
                        painter = painterResource(id = R.drawable.options_vertical),
                        contentDescription = "options",
                    )
                }
            }
        },
        colors = TopAppBarDefaults.centerAlignedTopAppBarColors().copy(
            containerColor = Color.Transparent
        )
    )
}


@Composable
fun ProfileHeader(
    userInfo: UserInfo,
    isCardListVisible: Boolean,
    setCardListVisible: (Boolean) -> Unit,
    isFollowed: Boolean?,
    toChat: (String) -> Unit,
    toFollow: (String, String) -> Unit,
    profileViewModel: ProfileViewModel,
) {
    Row(

    ) {
        // 头像
        AsyncImage(
            model = userInfo.avatar?.let {
                val url = "${Config.ADDRESS}avatars/$it"
                Log.d("MeRoute", "🟢 尝试加载头像 URL: $url")
                url
            },
            contentScale = ContentScale.Crop,
            contentDescription = "当前用户头像",
            modifier = Modifier
                .padding(end = 40.dp)
                .size(100.dp)
                .clip(shape = CircleShape),
            error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
        )
        // 数据统计
        Column(
            modifier = Modifier
                .padding(top = 10.dp)
        ) {
            Row(
                modifier = Modifier.padding(top = 20.dp),
                horizontalArrangement = Arrangement.SpaceEvenly,
            ) {
                ProfileStats(
                    title = "帖子",
                    count = userInfo.postCount,
                    userId = userInfo.id!!,
                    toFollow = toFollow,
                )
                Spacer(modifier = Modifier.width(50.dp))
                ProfileStats(
                    title = "粉丝",
                    count = userInfo.followerCount,
                    userId = userInfo.id,
                    toFollow = toFollow,
                )
                Spacer(modifier = Modifier.width(50.dp))
                ProfileStats(
                    title = "关注",
                    count = userInfo.followingCount,
                    userId = userInfo.id,
                    toFollow = toFollow,
                )
            }
        }
    }
    Row(

    ) {
        Column(

        ) {
            //简介
            userInfo.introduction?.let {
                Text(
                    text = it, modifier = Modifier
                        .padding(bottom = 5.dp)
                )
            }
            // 昵称
            userInfo.nickName?.let {
                Text(
                    text = it, modifier = Modifier
                        .padding(bottom = 5.dp)
                )
            }
        }

    }
    Row(
        horizontalArrangement = Arrangement.Center
    ) {
        // 如果详情页面是自己的页面，则显示编辑按钮和分享主页按钮
        if (userInfo.id == SessionManager.currentUser?.id) {
            // 按钮
            Button(
                onClick = { },
                colors = ButtonDefaults.buttonColors(
                    containerColor = InstagramLightGray,
                    contentColor = Color.Black
                ),
                modifier = Modifier
                    .height(30.dp)
                    .padding(horizontal = 4.dp)
                    .width(170.dp),
                shape = RoundedCornerShape(5.dp),
                elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp) // 设置内容内边距
            ) {
                Text(
                    text = "编辑主页",
                    fontSize = 12.sp,
                )
            }
            Button(
                onClick = {
                    toChat(userInfo.userName!!)
                },
                colors = ButtonDefaults.buttonColors(
                    containerColor = InstagramLightGray,
                    contentColor = Color.Black
                ),
                modifier = Modifier
                    .height(30.dp)
                    .padding(horizontal = 4.dp)
                    .width(170.dp),
                shape = RoundedCornerShape(5.dp),
                elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp) // 设置内容内边距
            ) {
                Text(
                    text = "分享主页",
                    fontSize = 12.sp,
                )
            }
        } else {
            // 按钮
            if (isFollowed == true) {
                Button(
                    onClick = {
                        // 取消关注
                        profileViewModel.updateIsFollowed(false)
                    },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = InstagramLightGray,
                        contentColor = Color.Black
                    ),
                    modifier = Modifier
                        .height(30.dp)
                        .padding(horizontal = 4.dp)
                        .width(170.dp),
                    shape = RoundedCornerShape(5.dp),
                    elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                    contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp) // 设置内容内边距
                ) {
                    Text(
                        text = "已关注",
                        fontSize = 12.sp,
                    )
                }
                Button(
                    onClick = {
                        toChat(userInfo.userName!!)
                    },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = InstagramLightGray,
                        contentColor = Color.Black
                    ),
                    modifier = Modifier
                        .height(30.dp)
                        .padding(horizontal = 4.dp)
                        .width(170.dp),
                    shape = RoundedCornerShape(5.dp),
                    elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                    contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp) // 设置内容内边距
                ) {
                    Text(
                        text = "发消息",
                        fontSize = 12.sp,
                    )
                }
            } else {
                Button(
                    onClick = {
                        // 关注
                        profileViewModel.updateIsFollowed(true)
                    },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = InstagramBlue,
                        contentColor = Color.White
                    ),
                    modifier = Modifier
                        .height(30.dp)
                        .padding(horizontal = 4.dp)
                        .width(170.dp),
                    shape = RoundedCornerShape(5.dp),
                    elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                    contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp) // 设置内容内边距
                ) {
                    Text(
                        text = "关注",
                        fontSize = 12.sp,
                    )
                }
                Button(
                    onClick = {
                        toChat(userInfo.userName!!)
                    },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = InstagramLightGray,
                        contentColor = Color.Black
                    ),
                    modifier = Modifier
                        .height(30.dp)
                        .padding(horizontal = 4.dp)
                        .width(170.dp),
                    shape = RoundedCornerShape(5.dp),
                    elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                    contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp) // 设置内容内边距
                ) {
                    Text(
                        text = "发消息",
                        fontSize = 12.sp,
                    )
                }
            }
        }

        // 控制卡片隐藏显示的按钮
        IconButton(
            onClick = {
                setCardListVisible(!isCardListVisible)
                Log.d("ProfilePage", "isCardListVisiable: $isCardListVisible")
            },
            modifier = Modifier
                .size(30.dp) // 统一按钮大小
                .clip(RoundedCornerShape(5.dp))
        ) {
            Image(
                painter = painterResource(id = if (isCardListVisible) R.drawable.plus_user_open else R.drawable.plus_user_closed),
                contentDescription = "plus_user",
                modifier = Modifier
                    .size(30.dp)
                    .background(InstagramLightGray)
            )
        }
    }
}

